package com.mzlalal.repeat.submit;

import cn.hutool.core.util.StrUtil;
import com.mzlalal.repeat.submit.aop.RepeatSubmitAspect;
import com.mzlalal.repeat.submit.prop.RepeatSubmitProperties;
import com.mzlalal.repeat.submit.service.RepeatSubmitPatternService;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RedissonClient;
import org.springframework.aop.aspectj.AspectJExpressionPointcutAdvisor;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * 防止重复提交自动配置类
 *
 * @author Mzlalal
 * @date 2021年4月19日 17:32:12
 **/
@Slf4j
@Configuration
@EnableConfigurationProperties(RepeatSubmitProperties.class)
@ConditionalOnProperty(name = "mz.repeat.submit.enable-repeat-submit", havingValue = "true")
public class RepeatSubmitAutoConfig {

    @Bean
    public RepeatSubmitPatternService repeatSubmitPatternService(RepeatSubmitProperties properties) {
        return new RepeatSubmitPatternService(properties);
    }

    @Bean
    public AspectJExpressionPointcutAdvisor repeatSubmitAspect(RedissonClient redissonClient, RepeatSubmitProperties properties
            , RepeatSubmitPatternService repeatSubmitPatternService) {
        // 切面不拦截IgnoreRepeatSubmit注解
        String expression = "!@annotation(com.mzlalal.repeat.submit.annotation.IgnoreRepeatSubmit)";
        if (StrUtil.isNotBlank(properties.getCustomExpression())) {
            expression = StrUtil.format("{} && {}", expression, properties.getCustomExpression());
        }
        // 声明切入点与切面
        AspectJExpressionPointcutAdvisor advisor = new AspectJExpressionPointcutAdvisor();
        advisor.setExpression(expression);
        advisor.setAdvice(new RepeatSubmitAspect(redissonClient, properties, repeatSubmitPatternService));
        return advisor;
    }
}
